<template>
	<div class="admin-auto-form">
		<x-border ref="xBorder" :border="border">
			<div v-if="async">
				<zk-auto-form @formLoad="formLoad" :serviceConfig="viewModel" @saveForm="saveForm" ref="zkAutoForm"></zk-auto-form>
			</div>
			<div v-else v-loading="vLoading"></div>
		</x-border>
	</div>
</template>

<script>
	import ala from 'ala'
	export default {
		props: {
			widgetData: {},
			title: {}
		},
		data() {
			return {
				async: false,
				viewModel: null,
				loading: true,
				border: null,
				firstLoad: true,
				vLoading: true
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			async init() {
				var type = this.$ala.urlType()
				if (this.widgetData.value) {
					type = this.widgetData.value.type
					if (!type && this.widgetData.value.form.type) {
						type = this.widgetData.value.form.type
					}
				}
				var para = {
					type: type,
					userId: this.$ala.urlId(),
					...this.$ala.urlToObject()
				}
				var response = await this.$ala.httpGet('api/Auto/Form', para)
				ala.info('表单信息', para, response)
				if (response) {
					this.viewModel = response
					this.async = true
				}
				this.$nextTick(() => {
					var diyBorder = null
					if (this.widgetData.value && this.widgetData.value.form) {
						diyBorder = this.widgetData.value.form.border
					}
					this.border = this.$ala.getBorder(this.viewModel.border, diyBorder)
					this.$refs.xBorder.init(this.border)
				})
				this.firstLoad = false
				this.vLoading = false
			},
			async saveForm(models) {
				if (this.$route.query.id) {
					models.id = this.$ala.getId()
				}
				let parameter = {
					type: this.viewModel.key,
					model: JSON.stringify(models),
					...this.$ala.urlToObject()
				}
				var apiUrl = 'api/auto/save'
				if (this.$ala.urlToParams()) {
					apiUrl += this.$ala.urlToParams()
				}
				var response = await this.$ala.httpPost(apiUrl, parameter)
				if (response) {
					this.$ala.toMessage(response)
				} else {
					if (this.$refs.zkAutoForm) {
						this.$refs.zkAutoForm.setSaveStatus(false)
					}
				}
			},
			formLoad(val) {
				if (val) {
					this.loading = false
				}
			},
			// 监听 x-widget值得变化,不能直接监听路由，直接监听路由可能会导致数据延迟
			watchWidget(val) {
				if (this.firstLoad === true) {
					return // 第一次加载，不监听路由，防止二次触发
				}
				// if (this.$ala.router().path !== '/Admin/AutoConfig/Edit') {
				//   return // 调转到其他页面时，不执行
				// }
				this.init().then(() => {
					this.$refs.zkAutoForm.$emit('form_change_widget_data', this.viewModel)
					this.$refs.xBorder.$emit('changeTitle', this.viewModel.name)
				})
			}
		}
	}
</script>

<style rel="stylesheet/scss" lang="scss">
	.admin-auto-form {
		min-height: 200px;

		.el-loading-mask {
			height: 800px;
		}
	}
</style>